﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace BigPang.Render
{
    public class Canvas
    {
        public static Canvas MainCanvas { get; private set; }

        public const int LayerCount = 3;

        public Camera Camrea = new Camera();

        HashSet<Renderable>[] mRenderList = new HashSet<Renderable>[LayerCount];

        public Graphics WindowGraph { get; private set; }

        public Graphics Graph { get; private set; }
        public Bitmap Buffer { get; set; }

        public Canvas(IntPtr windowHandle)
        {
            WindowGraph = Graphics.FromHwnd(windowHandle);
            Buffer = new Bitmap(1024, 1024);
            Graph = Graphics.FromImage(Buffer);
            Graph.CompositingMode = CompositingMode.SourceOver;
            Graph.CompositingQuality = CompositingQuality.HighSpeed;
            Graph.SmoothingMode = SmoothingMode.HighSpeed;
            Graph.InterpolationMode = InterpolationMode.Low;
            MainCanvas = this;

            for (int i = 0; i < LayerCount; i++)
            {
                mRenderList[i] = new HashSet<Renderable>();
            }
        }

        public void AddRender(Renderable render)
        {
            mRenderList[render.mLayer].Add(render);
        }

        public void RemoveRender(Renderable render)
        {
            mRenderList[render.mLayer].Remove(render);
        }

        public void Refresh( Graphics WinGraph )
        {
            WinGraph.Clear(Color.Black);
            Camrea.ProcessTick();
            WinGraph.DrawImageUnscaled(Buffer, Camrea.X, Camrea.Y);
            WinGraph.Flush();
        }

        public void Clear()
        {
            Graph.Clear(Color.Black);
        }

        public void RenderAll()
        {
            if (Map.TheMap != null)
            {
                Map.TheMap.render(Graph, 0);
                Map.TheMap.render(Graph, 1);
            }

            for (int i = 0; i < LayerCount; i++)
            {


                List<Renderable> renderList = mRenderList[i].ToList();

                try
                {
                    foreach (Renderable render in renderList)
                    {
                        render.OnRender(Graph);
                    }
                }
                catch (System.Exception ex)
                {

                }
            }

            if (Map.TheMap != null)
            {
                Map.TheMap.render(Graph, 2);
            }
          
        }
    }
}
